/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @param {number} targetSum
 * @return {number}
 */
var pathSum = function (root, targetSum) {
  //定义哈希表：前缀和->出现次数
  let map = new Map()
  //前缀和为0的出现一次
  map.set(0, 1)
  //目标前缀的出现次数
  let count = 0

  function dfs(node, currentSum) {
    if (!node) return

    //更新当前路径和
    currentSum += node.val
    //如果当前路径和减去targetSum在哈希表出现，看看前面有多少路径可以连接起来为目标值
    if (map.has(currentSum - targetSum)) {
      count += map.get(currentSum - targetSum)
    }
    //更新状态
    map.set(currentSum, (map.get(currentSum) || 0) + 1)

    //递归左、右子树
    dfs(node.left, currentSum)
    dfs(node.right, currentSum)

    //恢复状态
    map.set(currentSum, (map.get(currentSum) || 0) - 1)
  }
  dfs(root, 0)

  //返回结果
  return count
};